/*!
* @file    servo.c
* @version v1.0
* @date    2018-02-05
* @author  苏勇 suyong_yq@126.com
* @brief   基于CTIMER实现输出PWM控制舵机的功能
*/

#include "servo.h"
#include "fsl_ctimer.h"

/*
* CTIMER的计数时钟和寄存器访问接口时钟一样，来自于APB总线时钟：
* - CTIMER0/1/2的时钟来自于Sync APB
* - CTIMER3/4的时钟来自于Async APB
*/

/* 使用CTimer0控制输出PWM信号 */
#define CTIMER_SERVO CTIMER4

void Servo_Init(uint32_t initPosition)
{
    ctimer_config_t CTimerConfigStruct;

    CTimerConfigStruct.mode = kCTIMER_TimerMode;
    CTimerConfigStruct.prescale = SERVO_CTIMER_CLOCK_PRE_DIV-1U; /* 从时钟源到计数节拍的分频因子 */
    CTIMER_Init(CTIMER_SERVO, &CTimerConfigStruct);

#if 0
    /* BusClk即为AHB总线时钟(Sync/Async APB)
    *  初始化的占空比为0，有效值在0-100之间
    *  PWM信号的频率设定为50Hz
    *  在翻转点不产生中断
    */
    CTIMER_SetupPwm(CTIMER_SERVO, kCTIMER_Match_0,
        SERVO_PWM_DUTY_MID/100U, /* 将万分比转成百分比初始化输出的占空比 */
        50U,                /* PWM波形频率 */
        220000000UL,        /* 计数时钟源频率 */
        false               /* 是否在每个计数周期产生中断 */);
#endif
    CTIMER_SetupPwmPeriod(CTIMER_SERVO, SERVO_CTIMER_PWM_PERIOD_COUNT_VAL, (1U << kCTIMER_Match_0));
    Servo_SetPosition(initPosition);

    CTIMER_StartTimer(CTIMER_SERVO);
}

void Servo_SetPosition(uint32_t positionVal)
{
    //CTIMER_UpdatePwmDutycycle(CTIMER_SERVO, kCTIMER_Match_0, duty);
    //CTIMER_UpdatePwmDutycycleIn10000(CTIMER_SERVO, kCTIMER_Match_0, dutyIn10000);
    CTIMER_SetupPwmChannel(CTIMER_SERVO, kCTIMER_Match_0, SERVO_CTIMER_PWM_PERIOD_COUNT_VAL - positionVal);
}

/* EOF. */

